package com.za.plugin.transfer.func;



import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

import java.util.List;

// 把 convert('str',type) 改为 convert(type,'str')
public class ConvertFunctionTransfer implements FunctionTransfer {

    @Override
    public boolean isSupport(String sql) {
        // 在 isSupport 方法修改了 sql 字符串实际上不会影响原有的字符串，所以这里只是做个判断，实际修改操作还是要放到 transfer 方法
        return clearSpace(sql).contains("convert");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("convert\\s*\\(", "convert(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains("convert(")) {
            int idx = sql.indexOf("convert(");
            while (idx >= 0) {
                int left = sql.indexOf('(', idx);
                Content contentObj = StrUtil.getExpectContent(sql, left);
                int end = contentObj.getEnd();
                List<String> segmentList = StrUtil.getSegment(sql, left + 1, end - 1);
                sql = sql.substring(0, left + 1) + segmentList.get(1) + "," + segmentList.get(0) + ")" + sql.substring(end);
                idx = sql.indexOf("convert(", left);
            }
        }
        return sql;
    }
}
